// pages/chat/index.js
Page({
    data: {
        goodsId: '',
        conversationId: '',
        otherUserId: '',
        otherUserInfo: null,
        messages: [],
        inputContent: '',
        isLoading: true,
        isSending: false,
        messageWatch: null, // 消息监听对象
        pageNum: 1,
        hasMore: true,
        userInfo:{}
    },

    onLoad(options) {
        console.log(options);
        if (!options.otherUserId) {
            wx.navigateBack();
            return;
        }

        this.setData({
            conversationId: options.conversationId,
            otherUserId: options.otherUserId,
            goodsId: options.goodsId,
            userInfo:wx.getStorageSync('userInfo')
        });

        this.loadUserInfo();
        this.loadMessages();
        this.listenForRealtimeMessages();
    },

    // 加载对方用户信息
    loadUserInfo() {
        wx.cloud.callFunction({
            name: 'getSellerInfo',
            data: {
                sellerId: this.data.otherUserId
            },
            success: (res) => {
                console.log(res);
                wx.setNavigationBarTitle({
                    title: res.result.data.name
                  });
                this.setData({
                    otherUserInfo: res.result.data
                });
            },
            fail: (err) => {
                console.error('加载用户信息失败:', err);
            }
        });
    },

    // 加载消息列表
    loadMessages() {
        const {
            otherUserId,
            pageNum,goodsId
        } = this.data;

        wx.cloud.callFunction({
            name: 'getMessages',
            data: {
                fromUserId: this.data.userId,
                toUserId: otherUserId,
                pageNum: pageNum,
                goodsId:goodsId
            },
            success: (res) => {
                console.log(res);
                let newMessages = res.result.messages || [];

                // 如果是加载更多，将新消息添加到现有消息前面
                if (pageNum > 1) {
                    newMessages = [...newMessages, ...this.data.messages];
                }

                this.setData({
                    messages: newMessages,
                    isLoading: false,
                    hasMore: res.result.hasMore
                });

                // 滚动到底部
                this.scrollToBottom();
            },
            fail: (err) => {
                console.error('加载消息失败:', err);
                wx.showToast({
                    title: '加载消息失败',
                    icon: 'none'
                });
                this.setData({
                    isLoading: false
                });
            }
        });
    },

    // 监听实时消息
    listenForRealtimeMessages() {
        const db = wx.cloud.database();
        const {
            userId,
            otherUserId
        } = this.data;

        // 关闭已有监听
        if (this.messageWatch) {
            this.messageWatch.close();
        }

        // 监听当前会话的新消息
        this.messageWatch = db.collection('messages')
            .where({
                // 消息来自对方且未读
                fromUserId: otherUserId,
                toUserId: userId,
                isRead: false
            })
            .watch({
                onChange: (snapshot) => {
                    console.log('收到新消息:', snapshot);
                    this.handleNewMessages(snapshot.docChanges);
                },
                onError: (err) => {
                    console.error('监听消息失败:', err);
                }
            });
    },

    // 处理新消息
    handleNewMessages(changes) {
        let newMessages = [...this.data.messages];

        changes.forEach(change => {
            if (change.type === 'insert') {
                // 添加新消息到列表
                newMessages.push(change.doc);

                // 标记消息为已读
                this.markMessageAsRead(change.doc._id);
            }
        });

        if (newMessages.length > this.data.messages.length) {
            this.setData({
                messages: newMessages
            });
            this.scrollToBottom();
        }
    },

    // 标记消息为已读
    markMessageAsRead(messageId) {
        wx.cloud.callFunction({
            name: 'markMessageAsRead',
            data: {
                messageId: messageId,
                userId: this.data.userId
            }
        });
    },

    // 输入内容变化
    onInputChange(e) {
        this.setData({
            inputContent: e.detail.value
        });
    },

    // 发送消息
    sendMessage() {
        const {
            inputContent,
            otherUserId,goodsId
        } = this.data;

        if (!inputContent.trim()) {
            wx.showToast({
                title: '请输入消息内容',
                icon: 'none'
            });
            return;
        }

        this.setData({
            isSending: true
        });

        wx.cloud.callFunction({
            name: 'sendMessage',
            data: {
                fromUserId: wx.getStorageSync('userInfo')._id,
                toUserId: otherUserId,
                content: inputContent,
                contentType: 'text',
                goodsId: goodsId // 传递商品ID
            },
            success: (res) => {
                console.log(res);
                if (res.result.success) {
                    // 构建新消息对象
                    const newMessage = {
                        _id: res.result.messageId,
                        fromUserId: this.data.userId,
                        toUserId: otherUserId,
                        content: inputContent,
                        contentType: 'text',
                        createTime: new Date().toISOString(),
                        isRead: true
                    };

                    // 添加到消息列表
                    this.data.messages.push(newMessage);
                    this.setData({
                        messages: this.data.messages,
                        inputContent: '',
                        isSending: false
                    });

                    // 滚动到底部
                    this.scrollToBottom();
                } else {
                    wx.showToast({
                        title: res.result.message || '发送失败',
                        icon: 'none'
                    });
                    this.setData({
                        isSending: false
                    });
                }
            },
            fail: (err) => {
                console.error('发送消息失败:', err);
                wx.showToast({
                    title: '发送失败',
                    icon: 'none'
                });
                this.setData({
                    isSending: false
                });
            }
        });
    },

    // 滚动到底部
    scrollToBottom() {
        setTimeout(() => {
            wx.pageScrollTo({
                scrollTop: 999999,
                duration: 300
            });
        }, 100);
    },

    // 加载更多历史消息
    loadMoreMessages() {
        if (this.data.isLoading || !this.data.hasMore) return;

        this.setData({
            pageNum: this.data.pageNum + 1,
            isLoading: true
        });

        this.loadMessages();
    },

    // 页面卸载时清理
    onUnload() {
        // 关闭消息监听
        if (this.messageWatch) {
            this.messageWatch.close();
        }
    }
});